#include "settings.h"

#include <QDir>
#include <QFile>
#include <QByteArray>
#include <QJsonDocument>
#include <QDebug>

const Settings Settings::s_settings;

const Settings &Settings::Singleton(void)
{
    return s_settings;
}

Settings::Settings() {
    QFile cf(QDir::currentPath() + "/etc/config.json");
    if (!cf.open(QIODevice::ReadOnly)) {
        qFatal() << "Config file open failed: " << cf.fileName();
    } else {
        QJsonDocument jdoc =QJsonDocument::fromJson(cf.readAll());
        if (jdoc.isEmpty()) {
            qFatal() << "Config file has no data provided.";
        } else {
            m_json = jdoc.object();
            qInfo() << "Config data: " << m_json;
        }

    }
    cf.close();
}

int Settings::httpPort() const {
    QJsonObject obj = m_json.value("http").toObject();
    return obj.value("port").toInt();
}

QString Settings::httpRoutePath() const {
    QJsonObject obj = m_json.value("http").toObject();
    return obj.value("routePath").toString();
}

int Settings::scpPort() const {
    QJsonObject obj = m_json.value("scp").toObject();
    return obj.value("port").toInt();
}

QString Settings::scpAet() const {
    QJsonObject obj = m_json.value("scp").toObject();
    return obj.value("aeTitle").toString();
}

QString Settings::scpDbPath() const {
    QJsonObject obj = m_json.value("scp").toObject();
    QString path = obj.value("dbPath").toString();
    if (path.isEmpty()) {
        path = QDir::currentPath() + "/etc/wlistdb";
    }
    QDir().mkpath(path);
    return path;
}

QString Settings::logPath() const {
    QJsonObject obj = m_json.value("log").toObject();
    QString path = obj.value("path").toString();
    if (path.isEmpty()) {
        path = QDir::currentPath() + "/log";
    }
    QDir().mkpath(path);
    return path;
}

int Settings::logLevel(int defaultValue) const {
    QJsonObject obj = m_json.value("log").toObject();
    int level = obj.value("level").toInt(defaultValue);
    return level;
}

QString Settings::cardAet(QString defaultValue) const {
    QJsonObject obj = m_json.value("card").toObject();
    QString val = obj.value("aeTitle").toString();
    return val.isEmpty() ? defaultValue : val;
}

QString Settings::cardEndPoint(QString defaultValue) const {
    QJsonObject obj = m_json.value("card").toObject();
    QString val = obj.value("endPoint").toString();
    return val.isEmpty() ? defaultValue : val;
}

QString Settings::cardModality(QString defaultValue) const {
    QJsonObject obj = m_json.value("card").toObject();
    QString val = obj.value("modality").toString();
    return val.isEmpty() ? defaultValue : val;
}
